#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/3/26
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R34_EC_UpaidCreditInformationSummaryCheck
# @Software  :PyCharm

'''eof
name:申请企业未结清信贷业务为资产处置、垫款汇总、担保代偿或第三方代偿债务、欠息汇总的笔数校验
code:R34_EC_UpaidCreditInformationSummaryCheck
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''




import re
import sys
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = EC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['ReportNo'] in null_type_list:
                return [{}]
            # 存在空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def upaidCreditInformationSummaryCheck():
    """
    Factor1=max(未结清信贷信息概要(资产处置、欠息)（ECRSummaryUnsettled01）中的"由资产管理公司处置的债务（笔数）"，
    未结清由资产管理公司处置的债务（ECRUnpaidAssetDisp）中统计"信用报告编号"的数量）；
    Factor2=max(未结清信贷信息概要(资产处置、欠息)（ECRSummaryUnsettled01）中的"欠息汇总（笔数）"，
    未结清欠息（ECRUnpaidDebtInterest）中统计"信用报告编号"的数量）；
    Factor3=max(未结清信贷信息概要(垫款汇总、代偿)（ECRSummaryUnsettled04）中的"垫款汇总（笔数）"，
    未结清垫款（ECRUnpaidPaidback）中统计"信用报告编号"的数量）；
    Factor4=max(未结清信贷信息概要(垫款汇总、代偿)（ECRSummaryUnsettled04）中的"担保代偿或第三方代偿的债务（笔数）"，
    未结清担保代偿信息（ECRUnpaidGuarantee）中统计"信用报告编号"的数量）；
    Factor5=未结清担保代偿信息概要（ECRSummaryUnsettled03）中的"由担保公司代偿的债务笔数" + "由保险公司代偿的债务笔数"
    Factor=sum Factor{1~5}。

    :return:
    """
    # 新增加Factor5
    ECRSummaryUnsettled01 = getTable("ECRSummaryUnsettled01")
    ECRUnpaidAssetDisp = getTable("ECRUnpaidAssetDisp")
    ECRUnpaidDebtInterest = getTable("ECRUnpaidDebtInterest")
    ECRSummaryUnsettled04 = getTable("ECRSummaryUnsettled04")
    ECRUnpaidPaidback = getTable("ECRUnpaidPaidback")
    ECRUnpaidGuarantee = getTable("ECRUnpaidGuarantee")
    ECRSummaryUnsettled03 = getTable('ECRSummaryUnsettled03')

    if ECRSummaryUnsettled01 is None and ECRUnpaidAssetDisp is None and ECRUnpaidDebtInterest is None \
        and ECRSummaryUnsettled04 is None and ECRUnpaidPaidback is None and ECRUnpaidGuarantee is None:
        return u'缺失值'
    else:
        # Factor1
        if ECRSummaryUnsettled01 is None:
            result1 = None
        elif ECRSummaryUnsettled01 == [{}]:
            result1 = 0
        else:
            Debtsdamf_Number = ECRSummaryUnsettled01[0].get("Debtsdamf_Number")
            if isfloat(Debtsdamf_Number):
                result1 = float(Debtsdamf_Number)
            else:
                result1 = None
        if ECRUnpaidAssetDisp is None:
            result2 = None
        elif ECRUnpaidAssetDisp == [{}]:
            result2 = 0
        else:
            flag = []
            for i in ECRUnpaidAssetDisp:
                reportNo = i.get('ReportNo')
                if reportNo in null_type_list:
                    flag.append(None)
                else:
                    flag.append(1)
            flag = filter(lambda x:x is not None, flag)
            if len(flag) == 0:
                result2 = None
            else:
                result2 = sum(flag)
        if result1 is None and result2 is None:
            Factor1 = None
        else:
            if result1 is None:
                result1 = 0
            if result2 is None:
                result2 = 0
            Factor1 = max(result1, result2)

        #Factor2
        if ECRSummaryUnsettled01 is None:
            result1 = None
        elif ECRSummaryUnsettled01 == [{}]:
            result1 = 0
        else:
            OweBalancesum_Number = ECRSummaryUnsettled01[0].get("OweBalancesum_Number")
            if isfloat(OweBalancesum_Number):
                result1 = float(OweBalancesum_Number)
            else:
                result1 = None
        if ECRUnpaidDebtInterest is None:
            result2 = None
        elif ECRUnpaidDebtInterest == [{}]:
            result2 = 0
        else:
            flag = []
            for i in ECRUnpaidDebtInterest:
                reportNo = i.get('ReportNo')
                if reportNo in null_type_list:
                    flag.append(None)
                else:
                    flag.append(1)
            flag = filter(lambda x:x is not None, flag)
            if len(flag) == 0:
                result2 = None
            else:
                result2 = sum(flag)
        if result1 is None and result2 is None:
            Factor2 = None
        else:
            if result1 is None:
                result1 = 0
            if result2 is None:
                result2 = 0
            Factor2 = max(result1, result2)

        # Factor3
        if ECRSummaryUnsettled04 is None:
            result1 = None
        elif ECRSummaryUnsettled04 == [{}]:
            result1 = 0
        else:
            PaidbackBalancesum_Number = ECRSummaryUnsettled04[0].get("PaidbackBalancesum_Number")
            if isfloat(PaidbackBalancesum_Number):
                result1 = float(PaidbackBalancesum_Number)
            else:
                result1 = None
        if ECRUnpaidPaidback is None:
            result2 = None
        elif ECRUnpaidPaidback == [{}]:
            result2 = 0
        else:
            flag = []
            for i in ECRUnpaidPaidback:
                reportNo = i.get('ReportNo')
                if reportNo in null_type_list:
                    flag.append(None)
                else:
                    flag.append(1)
            flag = filter(lambda x:x is not None, flag)
            if len(flag) == 0:
                result2 = None
            else:
                result2 = sum(flag)
        if result1 is None and result2 is None:
            Factor3 = None
        else:
            if result1 is None:
                result1 = 0
            if result2 is None:
                result2 = 0
            Factor3 = max(result1, result2)

        # Factor4
        if ECRSummaryUnsettled04 is None:
            result1 = None
        elif ECRSummaryUnsettled04 == [{}]:
            result1 = 0
        else:
            Guarantee_Number = ECRSummaryUnsettled04[0].get("Guarantee_Number")
            if isfloat(Guarantee_Number):
                result1 = float(Guarantee_Number)
            else:
                result1 = None
        if ECRUnpaidGuarantee is None:
            result2 = None
        elif ECRUnpaidGuarantee == [{}]:
            result2 = 0
        else:
            flag = []
            for i in ECRUnpaidGuarantee:
                reportNo = i.get('ReportNo')
                if reportNo in null_type_list:
                    flag.append(None)
                else:
                    flag.append(1)
            flag = filter(lambda x:x is not None, flag)
            if len(flag) == 0:
                result2 = None
            else:
                result2 = sum(flag)
        if result1 is None and result2 is None:
            Factor4 = None
        else:
            if result1 is None:
                result1 = 0
            if result2 is None:
                result2 = 0
            Factor4 = max(result1, result2)

        # 新增加Factor5
        if ECRSummaryUnsettled03 is None:
            Factor5 = None
        elif ECRSummaryUnsettled03 == [{}]:
            Factor5 = 0
        else:
            GuaranteeNum = ECRSummaryUnsettled03[0].get('GuaranteeNum')
            InsuranceNum = ECRSummaryUnsettled03[0].get('InsuranceNum')
            if isfloat(GuaranteeNum) is None and isfloat(InsuranceNum) is None:
                Factor5 = None
            else:
                if isfloat(GuaranteeNum) is None:
                    GuaranteeNum = 0
                if isfloat(InsuranceNum) is None:
                    InsuranceNum = 0
                Factor5 = GuaranteeNum + InsuranceNum

        if Factor1 is None and Factor2 is None and Factor3 is None and Factor4 is None and Factor5 is None:
            return u'缺失值'
        else:
            if Factor1 is None:
                Factor1 = 0
            if Factor2 is None:
                Factor2 = 0
            if Factor3 is None:
                Factor3 = 0
            if Factor4 is None:
                Factor4 = 0
            if Factor5 is None:
                Factor5 = 0
            Factor = Factor1 + Factor2 + Factor3 + Factor4 + Factor5
            return round(Factor, 4)



result = upaidCreditInformationSummaryCheck()









